# -*- coding: utf-8 -*-
from urllib.parse import urlparse
from django.db import transaction
#from django.utils.text import slugify
from uuslug import slugify
from django.contrib.auth.models import User as AuthUser
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from common.models import Site, SiteTaxonomy, CategoryTaxonomy, UserProfile
from blog.models import Category, Article, ArticleContent
from blog.models import ArticleSource, ArticleStatus, ArticleInputFormat


def get_author(author_name, site, username=None, email=None):
    """
    获取用户
    """
    user = None
    if not username:
        username = slugify(author_name)
    try:
        user = AuthUser.objects.get(username=username, profile__site=site)
    except ObjectDoesNotExist:
        with transaction.atomic():
            if not email:
                start = site.url.find(site.slug)
                end = site.url.find('/', start)
                if end == -1:
                    postfix = site.url[start:]
                else:
                    postfix = site.url[start:end]
                email = username + '@' + postfix
            user = AuthUser.objects.create_user(
                username, email, first_name=author_name)
            user.save()
            user_profile = UserProfile(user=user, site=site)
            user_profile.save()
    return user


def save_article(site_id, article):
    site = Site.objects.get(pk=site_id)
    _save_article(site, article)
    return None


def _save_article(site, article):
    un_cat = get_uncategorized()
    with transaction.atomic():
        try:
            if 'object_key_int' in article:
                model_source = ArticleSource.objects.get(
                    object_key_int=article['object_key_int'], site=site)
            elif 'object_key_str' in article:
                model_source = ArticleSource.objects.get(
                    object_key_str=article['object_key_str'], site=site)
            # model = Article.objects.get(id == model_source.article_id)
            # model_content = ArticleContent.objects.get(id == model.id)
        except (ObjectDoesNotExist, ArticleSource.DoesNotExist):
            if 'slug' in article:
                slug = slugify(article['slug'])
            else:
                slug = slugify(article['title'])
            author = get_author(
                article['author_name'], site, article.get('author_username', ''))
            if 'cats' in article:
                cats = [get_cat(cat, author) for cat in article['cats']]
            else:
                cats = [un_cat, ]
            tags = [get_tag(tag, author) for tag in article['tags']]
            model = Article(title=article['title'], summary=article['content'][:20] + '...',
                            slug=slug, author=author,
                            # tags=tags,categories=cats,
                            status=ArticleStatus.Draft,
                            post_at=article['post_at'],)
            model.save()
            model.categories.add(*cats)
            model.tags.add(*tags)
            model_content = ArticleContent(article=model,
                                           display_content=article[
                                               'content'],
                                           input_content=article[
                                               'content'],
                                           input_format=ArticleInputFormat.Html,)
            model_source = ArticleSource(article=model,
                                         site=site,
                                         url=article['source_url'],
                                         content=article['source_content'])
            if 'object_key_int' in article:
                model_source.object_key_int = article['object_key_int']
            elif 'object_key_str' in article:
                model_source.object_key_str = article['object_key_str']
            model_content.save()
            model_source.save()


def save_articles(site, articles):
    """
    保存文字列表
    """
    for article in articles:
        save_article(site, article)


def get_site(site_url, name, slug=None):
    """
    获取站点
    """
    site = None
    try:
        site = Site.objects.get(url=site_url, taxonomy=SiteTaxonomy.Blog)
    except ObjectDoesNotExist:
        if not slug:
            o = urlparse(site_url)
            slug = o.netloc
        site = Site(url=site_url, slug=slug,
                    taxonomy=SiteTaxonomy.Blog, name=name)
        site.save()
    return site


def get_cat(name, author, slug=None):
    """
    获取分类
    """
    cat = None
    need_create = False
    try:
        cat = Category.objects.filter(
            name=name, taxonomy=CategoryTaxonomy.Category).first()
        need_create = not (cat and cat.id > 0)

    except ObjectDoesNotExist:
        need_create = True
    if need_create:
        if not slug:
            slug = slugify(name)
        cat = Category(name=name, slug=slug,
                       taxonomy=CategoryTaxonomy.Category, created_by=author)
        cat.save()
    return cat


def get_local_site():
    """
    获取本站
    """
    return get_site('http://localhost', '本站', 'self-site')


def get_anonymous():
    """
    获取匿名用户
    """
    site = get_local_site()
    return get_author('匿名', site, 'anonymous')


def get_uncategorized():
    """
    获取默认分类
    """
    author = get_anonymous()
    return get_cat('Uncategorized', author, 'uncategorized')


def get_tag(name, author, slug=None):
    """
    获取标签
    """
    tag = None
    need_create = False
    try:
        tag = Category.objects.filter(name=name, taxonomy=CategoryTaxonomy.Tag).first()
        need_create = not (tag and tag.id>0)
    except ObjectDoesNotExist:
        need_create = True
    if need_create:        
        if not slug:
            slug = slugify(name)
        tag = Category(name=name, slug=slug,
                       taxonomy=CategoryTaxonomy.Tag, created_by=author)
        tag.save()
    return tag
